<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      data: []
    }
  },
  methods: {
    handleSuccess({ header, results }) {
      console.log(results)
      this.data = this.transExcel(results)
      this.doImport(this.data)
    },
    // 批量导入数据
    async doImport(data) {
      const res = await importEmployee(data)
      console.log(res)
      // 导入成功
      this.$message.success(res.message)
      // 跳转回原页面
      this.$router.push('/employees')
    },
    transExcel(result) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 写代码
      return result.map(item => {
        const obj = {}
        const keys = Object.keys(item)
        keys.forEach(items => {
          const enkey = mapInfo[items]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            obj[enkey] = new Date(formatExcelDate(item[items]))
          } else {
            obj[enkey] = item[items]
          }
        })
        return obj
      })
    }
  }
}
</script>
